<template>
  <div class="app-container">
    <!-- 搜索和操作区域保持不变 -->
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="食谱名称" prop="recipeName">
        <el-input
          v-model="queryParams.recipeName"
          placeholder="请输入食谱名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Pointer"
          :disabled="multiple"
          @click="handleAllVerify"
          v-hasPermi="['manage:recipe:edit']"
          >一键审批</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      :data="recipeList"
      v-loading="loading"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" width="50" align="center" />
      <el-table-column prop="recipeName" label="食谱名称" align="center" />
      <el-table-column label="早餐" align="center">
        <template #default="scope">
          <el-popover
            placement="right"
            width="400"
            trigger="click"
            v-if="
              scope.row.breakfastRecipe &&
              JSON.parse(scope.row.breakfastRecipe).length > 0
            "
          >
            <template #reference>
              <el-button link type="primary">查看早餐</el-button>
            </template>
            <div class="meal-detail">
              <div
                v-for="(item, index) in JSON.parse(scope.row.breakfastRecipe)"
                :key="`breakfast-${index}`"
                class="meal-item"
              >
                <p><strong>食材名称：</strong>{{ item.foodName }}</p>
                <p><strong>备注：</strong>{{ item.remark }}</p>
                <el-divider
                  v-if="
                    index < JSON.parse(scope.row.breakfastRecipe).length - 1
                  "
                />
              </div>
            </div>
          </el-popover>
          <span v-else>无早餐数据</span>
        </template>
      </el-table-column>
      <el-table-column label="午餐" align="center">
        <template #default="scope">
          <el-popover
            placement="right"
            width="400"
            trigger="click"
            v-if="
              scope.row.lunchRecipe &&
              JSON.parse(scope.row.lunchRecipe).length > 0
            "
          >
            <template #reference>
              <el-button link type="primary">查看午餐</el-button>
            </template>
            <div class="meal-detail">
              <div
                v-for="(item, index) in JSON.parse(scope.row.lunchRecipe)"
                :key="`lunch-${index}`"
                class="meal-item"
              >
                <p><strong>食材名称：</strong>{{ item.foodName }}</p>
                <p><strong>备注：</strong>{{ item.remark }}</p>
                <el-divider
                  v-if="index < JSON.parse(scope.row.lunchRecipe).length - 1"
                />
              </div>
            </div>
          </el-popover>
          <span v-else>无午餐数据</span>
        </template>
      </el-table-column>
      <el-table-column label="晚餐" align="center">
        <template #default="scope">
          <el-popover
            placement="right"
            width="400"
            trigger="click"
            v-if="
              scope.row.dinnerRecipe &&
              JSON.parse(scope.row.dinnerRecipe).length > 0
            "
          >
            <template #reference>
              <el-button link type="primary">查看晚餐</el-button>
            </template>
            <div class="meal-detail">
              <div
                v-for="(item, index) in JSON.parse(scope.row.dinnerRecipe)"
                :key="`dinner-${index}`"
                class="meal-item"
              >
                <p><strong>食材名称：</strong>{{ item.foodName }}</p>
                <p><strong>备注：</strong>{{ item.remark }}</p>
                <el-divider
                  v-if="index < JSON.parse(scope.row.dinnerRecipe).length - 1"
                />
              </div>
            </div>
          </el-popover>
          <span v-else>无晚餐数据</span>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" align="center">
        <template #default="scope">
          {{ parseTime(scope.row.createTime, "{y}-{m}-{d}") }}
        </template>
      </el-table-column>
      <el-table-column
        prop="remark"
        label="备注"
        show-overflow-tooltip
        align="center"
      />
      <el-table-column prop="verifyFlag" label="审批状态" align="center">
        <template #default="scope">
          <el-tag
            :type="
              scope.row.verifyFlag === 1
                ? 'success'
                : scope.row.verifyFlag === 0
                ? 'warning'
                : 'danger'
            "
            disable-transitions
            >{{
              scope.row.verifyFlag === 1
                ? "已审批"
                : scope.row.verifyFlag === 0
                ? "待审批"
                : "已驳回"
            }}</el-tag
          >
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button
            size="small"
            type="primary"
            @click="handleDetail(scope.row)"
            v-hasPermi="['manage:recipe:list']"
            >查看</el-button
          >
          <el-button
            size="small"
            type="success"
            @click="handleVerify(scope.row, 1)"
            v-hasPermi="['manage:recipe:edit']"
            v-if="scope.row.verifyFlag === 0"
            >通过</el-button
          >
          <!-- <el-button
            size="small"
            type="danger"
            @click="handleVerify(scope.row, 3)"
            v-hasPermi="['manage:recipe:edit']"
            v-if="scope.row.verifyFlag === 1"
            >退回</el-button
          > -->
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改食谱管理对话框 -->
    <el-dialog :title="title" v-model="open" width="550px" append-to-body>
      <el-form ref="recipeRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="食谱名称" prop="recipeName">
          <el-input v-model="form.recipeName" placeholder="请输入食谱名称" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            type="textarea"
            :rows="2"
            v-model="form.remark"
            placeholder="请输入备注"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看食谱管理对话框 -->
    <el-dialog :title="title" v-model="detailOpen" width="600px" append-to-body>
      <el-tabs v-model="activeDetailTab" type="card" class="detail-tabs">
        <!-- 早餐食谱 -->
        <el-tab-pane label="早餐" name="breakfast">
          <div
            v-for="(item, index) in detailRecipe.breakfastRecipe"
            :key="`breakfast-${index}`"
            class="recipe-item"
          >
            <p><strong>食材名称：</strong>{{ item.foodName }}</p>
            <p><strong>备注：</strong>{{ item.remark }}</p>
            <el-divider
              v-if="index < detailRecipe.breakfastRecipe.length - 1"
            />
          </div>
        </el-tab-pane>

        <!-- 午餐食谱 -->
        <el-tab-pane label="午餐" name="lunch">
          <div
            v-for="(item, index) in detailRecipe.lunchRecipe"
            :key="`lunch-${index}`"
            class="recipe-item"
          >
            <p><strong>食材名称：</strong>{{ item.foodName }}</p>
            <p><strong>备注：</strong>{{ item.remark }}</p>
            <el-divider v-if="index < detailRecipe.lunchRecipe.length - 1" />
          </div>
        </el-tab-pane>

        <!-- 晚餐食谱 -->
        <el-tab-pane label="晚餐" name="dinner">
          <div
            v-for="(item, index) in detailRecipe.dinnerRecipe"
            :key="`dinner-${index}`"
            class="recipe-item"
          >
            <p><strong>食材名称：</strong>{{ item.foodName }}</p>
            <p><strong>备注：</strong>{{ item.remark }}</p>
            <el-divider v-if="index < detailRecipe.dinnerRecipe.length - 1" />
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>

    <!-- 退回原因对话框 -->
    <!-- <el-dialog title="退回原因" v-model="rejectDialogVisible" width="500px">
      <el-form>
        <el-form-item>
          <el-input
            type="textarea"
            :rows="4"
            v-model="returnReason"
            placeholder="请输入退回原因"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="rejectDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmReject">确定</el-button>
      </template>
    </el-dialog> -->
  </div>
</template>

<script setup name="Examine">
import { listRecipe, getRecipe, delRecipe, addRecipe, updateRecipe, batchUpdateRecipe } from "@/api/manage/recipe"

const { proxy } = getCurrentInstance()

const recipeList = ref([])
const open = ref(false)
const detailOpen = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const detailRecipe = ref({})
const activeDetailTab = ref('breakfast') // 添加这行，设置默认激活的tab

const data = reactive({
  form: {
    breakfastList: [],
    lunchList: [],
    dinnerList: []
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    recipeName: null,
    isVerifying: null
  },
  rules: {
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询食谱管理列表 */
function getList () {
  loading.value = true
  queryParams.value.isVerifying = 'verifying'
  listRecipe(queryParams.value).then(response => {
    recipeList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel () {
  open.value = false
  reset()
}

// 表单重置
function reset () {
  form.value = {
    recipeId: null,
    recipeName: null,
    breakfastRecipe: null,
    lunchRecipe: null,
    dinnerRecipe: null,
    userId: null,
    createTime: null,
    breakfastList: [],
    lunchList: [],
    dinnerList: []
  }
  proxy.resetForm("recipeRef")
}

/** 搜索按钮操作 */
function handleQuery () {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery () {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange (selection) {
  // ids为多选框选中的未通过审批的id
  ids.value = selection.map(item => {
    if (item.verifyFlag === 0) {
      return item.recipeId
    }
  })
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

function handleAllVerify () {
  proxy.$modal.confirm('确定要一键审批选中的食谱吗？').then(function () {
    return batchUpdateRecipe(ids.value)
  }).then(res => {
    getList()
    if (res.code === 200) {
      proxy.$modal.msgSuccess("一键审批成功")
    }
  }).catch(() => { })
}

/** 新增按钮操作 */
function handleAdd () {
  reset()
  open.value = true
  title.value = "添加食谱管理"
}

/** 修改按钮操作 */
function handleUpdate (row) {
  reset()
  const _recipeId = row.recipeId || ids.value
  getRecipe(_recipeId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改食谱管理"
  })
}

/** 查看按钮操作 */
function handleDetail (recipe) {
  const _recipeId = recipe.recipeId || ids.value
  getRecipe(_recipeId).then(response => {
    detailRecipe.value = response.data
    // 将json转换为数组
    detailRecipe.value.breakfastRecipe = JSON.parse(detailRecipe.value.breakfastRecipe)
    detailRecipe.value.lunchRecipe = JSON.parse(detailRecipe.value.lunchRecipe)
    detailRecipe.value.dinnerRecipe = JSON.parse(detailRecipe.value.dinnerRecipe)
    // 重置activeTab为默认值
    activeDetailTab.value = 'breakfast'
    detailOpen.value = true
    title.value = "食谱详情"
  })
}

/** 提交按钮 */
function submitForm () {
  proxy.$refs["recipeRef"].validate(valid => {
    if (valid) {
      if (form.value.recipeId != null) {
        updateRecipe(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        // 提取数据
        const recipeData = {}
        recipeData.recipeName = form.value.recipeName
        recipeData.remark = form.value.remark
        // 移除 popoverVisible 字段并转换为 JSON 字符串
        recipeData.breakfastRecipe = JSON.stringify(
          form.value.breakfastList.map(item => {
            const { popoverVisible, ...rest } = item // 解构赋值，移除 popoverVisible
            return rest
          })
        )
        recipeData.lunchRecipe = JSON.stringify(
          form.value.lunchList.map(item => {
            const { popoverVisible, ...rest } = item // 解构赋值，移除 popoverVisible
            return rest
          })
        )
        recipeData.dinnerRecipe = JSON.stringify(
          form.value.dinnerList.map(item => {
            const { popoverVisible, ...rest } = item // 解构赋值，移除 popoverVisible
            return rest
          })
        )
        addRecipe(recipeData).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete (row) {
  const _recipeIds = row.recipeId || ids.value
  const delName = _recipeIds.length >= 1 ? '选中的食谱' : row.recipeName
  proxy.$modal.confirm('确定要删除' + delName + '吗？').then(function () {
    return delRecipe(_recipeIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => { })
}

// 新增进食记录
function handleAddItem (mealType) {
  if (mealType === 'breakfast') {
    form.value.breakfastList.push({})
  } else if (mealType === 'lunch') {
    form.value.lunchList.push({})
  } else {
    form.value.dinnerList.push({})
  }
}

// 删除进食记录
function handleRemoveItem (index, mealType) {
  if (mealType === 'breakfast') {
    form.value.breakfastList.splice(index, 1)
  } else if (mealType === 'lunch') {
    form.value.lunchList.splice(index, 1)
  } else {
    form.value.dinnerList.splice(index, 1)
  }
}

const rejectDialogVisible = ref(false)
const returnReason = ref('')
const currentRejectRecipe = ref(null)

function handleVerify (row, flag) {
  if (flag === 1) {
    // 通过逻辑保持不变
    const _recipeId = row.recipeId
    const verifyName = row.recipeName
    proxy.$modal.confirm('确定要通过' + verifyName + '吗？').then(
      updateRecipe({
        recipeId: _recipeId,
        verifyFlag: 1
      })
    ).then(() => {
      getList()
      proxy.$modal.msgSuccess("操作成功")
    }).catch(() => { })
  } else {
    // 退回逻辑修改
    currentRejectRecipe.value = row
    rejectDialogVisible.value = true
  }
}

// function confirmReject () {
//   if (!returnReason.value) {
//     proxy.$modal.msgWarning('请输入退回原因')
//     return
//   }

//   updateRecipe({
//     recipeId: currentRejectRecipe.value.recipeId,
//     verifyFlag: 2,
//     returnReason: returnReason.value
//   }).then(() => {
//     getList()
//     proxy.$modal.msgSuccess("退回成功")
//     rejectDialogVisible.value = false
//     returnReason.value = ''
//   })
// }

getList()
</script>

<style scoped>
.meal-detail {
  padding: 10px;
}

.meal-item {
  margin-bottom: 10px;
}

.meal-item p {
  margin: 5px 0;
  font-size: 14px;
}
</style>